package cn.study.zgm.nettyall.channel;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * packageName cn.study.zgm.nettyall.channel
 *
 * @author 你的名字
 * @version JDK 8
 * @className TestByteBuffer (此处以class为例)
 * @date 2025/2/23
 * @description TODO
 */
@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) {
        try (FileChannel channel = new FileInputStream("byteBufferTest.txt").getChannel()){
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true){
                final int read = channel.read(buffer); // 从channel读取数据，向buffer吸入
                if (read==-1){ // 读取为-1，表示已经读取完，没有数据
                    log.error("channel已经读取结束！");
                    break;
                }
                log.info("channel读取到的字节数是{}",read);
                buffer.flip(); // 切换至读模式
                while (buffer.remaining()>0){
                    final byte b = buffer.get();
                    log.info("channel读取到的字节是{}",b);
                }
                buffer.clear(); // 切换至写模式
            }
            log.info("channel已经读结束");
//            final int remaining = buffer.remaining();
            final byte b = buffer.get();
        }catch (Exception e){

        }
    }
}
